<?php
namespace app\admin\controller;
use app\admin\common\Base;
use think\Loader;
use think\Db;
class Index extends Base {
	public function index() {
		$this -> isLogin();
		return $this -> view -> fetch('index');
	}
	public function welcome() {
		return $this -> view -> fetch('welcome');
	}
	public function ticket() {
		Loader::import('org.wxBizMsgCrypt', EXTEND_PATH);
		$encodingAesKey = config('$encodingAesKey');
		$token = config('$token');
		$appId = config('$appId');
		$timeStamp = empty($_GET['timestamp']) ? "" : trim($_GET['timestamp']);
		$nonce = empty($_GET['nonce']) ? "" : trim($_GET['nonce']);
		$msg_sign = empty($_GET['msg_signature']) ? "" : trim($_GET['msg_signature']);
		$encryptMsg = file_get_contents('php://input');
		$data = [
			'key' => $encryptMsg
		];
		if ($encryptMsg) {
//			Db::table('ticket')->insert($data);
			file_put_contents('./uploads/test.log', $encryptMsg);
		}
		$pc = new \WXBizMsgCrypt($token,$encodingAesKey,$appId);
		$xml_tree = new \DOMDocument();
		$xml_tree -> loadXML($encryptMsg);
		$array_e = $xml_tree -> getElementsByTagName('Encrypt');
		$encrypt = $array_e -> item(0) -> nodeValue;
		$format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
		$from_xml = sprintf($format, $encrypt);
		
		// 第三方收到公众号平台发送的消息
		$msg = '';
		$errCode = $pc -> decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
		if ($errCode == 0) {
			$xml = new \DOMDocument();
			$xml -> loadXML($msg);
			$array_e = $xml -> getElementsByTagName('ComponentVerifyTicket');
			$component_verify_ticket = $array_e -> item(0) -> nodeValue;
			file_put_contents('./uploads/ticket.log', $component_verify_ticket);
			echo 'success';

		} else {
			file_put_contents('./uploads/error.log', '执行了错误--'.$errCode.'\n',FILE_APPEND);
			print($errCode . "\n");
		}
		die();
	}
	public function callback ()
	{
		$auth_code = input('param.auth_code');
//		var_dump($auth_code);
		return $this->fetch('index/callback');
	}
	public function shouquan ()
	{
		$pre_auth_code = $this->get_pre_auth_code();
		$appId = config('$appId');
		$callback = 'https://edu.qian-hong.com/callback.html';
		$url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={$appId}&pre_auth_code={$pre_auth_code}&redirect_uri={$callback}&auth_type=1";
		$this->assign('url',$url);
		return $this->fetch('index/ticket');
	}

}
